package com.mars.common.utils.ali;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

public class MyOSSUtils {

    //OSS上传文件
    public static String uploadFile(MultipartFile file, OSSConfig ossConfig) {
        OSSConfig config = ossConfig;
        OSS ossClient = null;
        String fileName = file.getOriginalFilename();
        String folder = contentType(fileName.substring(fileName.lastIndexOf(".") + 1), ossConfig);
        String objectName = folder + UUID.randomUUID() + fileName;
        //如果没有下面这两行代码，访问url将不会预览而是直接下载下来
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("image/jpg");

        try {
            ossClient = new OSSClientBuilder().build(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());
            ossClient.putObject(config.getBucketName(), objectName, new ByteArrayInputStream(file.getBytes()), metadata);
            String[] url = getUrl(objectName, ossConfig).split("\\?");
            return url[0];
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }

    //获得URL连接
    public static String getUrl(String objectName, OSSConfig ossConfig) {
        OSSConfig config = ossConfig;
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        //生成URL
        OSS ossClient = new OSSClientBuilder().build(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());
        URL url = ossClient.generatePresignedUrl(config.getBucketName(), objectName, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }

    //根据文件类型分配文件夹
    private static String contentType(String fileType, OSSConfig ossConfig) {
        fileType = fileType.toLowerCase();
        String folder = "";
        switch (fileType) {
            case "bmp":
            case "gif":
            case "png":
            case "jpg":
            case "jpeg":
                folder = "images/";
                break;

            case "html":
            case "txt":
            case "xml":
                folder = "text/";
                break;

            case "map3":
                folder = "map3/";
                break;

            case "vsd":
            case "ppt":
            case "pptx":
            case "doc":
            case "docx":
                folder = "application/";
                break;
            case "mp4":
                folder = "video/";
                break;
        }
        return folder;
    }

    /**
     * 本地文件上传
     *
     * @param path
     */
    public static void updateLocalDocument(String path, String fileName, OSSConfig ossConfig) {
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "yourEndpoint";
// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());

// 创建PutObjectRequest对象。
// 填写Bucket名称、Object完整路径和本地文件的完整路径。Object完整路径中不能包含Bucket名称。
// 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(), fileName, new File(path));

// 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);

// 上传文件。
        ossClient.putObject(putObjectRequest);

// 关闭OSSClient。
        ossClient.shutdown();
    }

    /**
     * 删除阿里对象云文件
     *
     * @param documentName
     */
    public static void delete(String documentName, OSSConfig ossConfig) {
        OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        ossClient.deleteObject(ossConfig.getBucketName(), documentName);
    }


}


